# -*- coding: cp866 -*-

import MSData
import WorkerMSAPI
import WorkerMSDB
import MSLogger
import MSDBTemplates

import BaseHTTPServer
import time
import datetime
import os
import sys
import pdb

MSLogger.logInit('logs\\ms.online.log', 6, True)
globalHost = '192.168.4.4'
#globalHost = '31.28.8.37'
globalPort = 8085
globalObjectId = 7

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def getObjects(self, c):
        objs = []
        objs_test = []
        objs_norm = []
        MSDBTemplates.GET_MSObjects_FROM_CarOnline(c, objs)
        MSDBTemplates.GET_MSObjects_FROM_CarOnline(c, objs, 'fast')

        try:
            f = open('C:\\Magic\\ms.online.normal_objects.2.cfg', 'r')
        except:
            return ([], objs)

        norm_ids = []
        for o in f.readlines():
            o = o.strip()
            if len(o): norm_ids.append(o)

        for o in objs:
            if str(o.objectPCNId) in norm_ids:
                objs_norm.append(o)
            else:
                objs_test.append(o)
        return (objs_test, objs_norm)

    def getNormalObjects(self, c):
        return self.getObjects(c)[1]

    def getAllObjects(self, c):
        t, n = self.getObjects(c)
        return t + n

    def mode_normal(self, one_oid=None):
        #reader = WorkerMSDB.Worker('192.168.4.5', '50359', 'transferTest', 'sa', 'ms-004')
        reader = WorkerMSDB.Worker('192.168.4.5', '52655', 'transferTest', 'sa', 'ms-004')
        #import pdb; pdb.set_trace()
        reader.connect()

        objects = self.getNormalObjects(reader.connection.cursor())
        c = reader.connection.cursor()
        online_ctr = 0
        offline_ctr = 0
        self.wfile.write('<script type="text/JavaScript"> setTimeout("location.reload(true);", 30000); </script>')
        #self.wfile.write("<script type='text/JavaScript'>for(i=0;i<document.all.tags('blink').length;i++){s=document.all.tags('blink')[i]; s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';}</script>")
        self.wfile.write('<style type="text/css">')
        self.wfile.write('td.tdblue {color: #ffffff; background: #6699cc; font-family: Arial, sans-serif; font-weight: bold; font-size: 14px; }')
        self.wfile.write('td.tblue { color: #ffffff; background: #006699; font-family: Arial, sans-serif; font-weight: bold; font-size: 14px;}')
        self.wfile.write('td.tdred {FONT-WEIGHT: bold; FONT-SIZE: 14px; BACKGROUND: pink;  COLOR: #000000; FONT-FAMILY: Arial, sans-serif; }')
        self.wfile.write('</style>')
        self.wfile.write('<table border=1>')
        self.wfile.write('<tr><td class="tblue">Object</td><td class="tblue">MS number</td><td class="tblue">Status (min ago)</td><td class="tblue">Signal</td><td class="tblue">Operator</td></tr>')
        od = {}
        for o in objects:
            if one_oid != None and int(o.objectPCNId) == int(one_oid):
                od.clear()
                od[int(o.objectPCNId)] = o
                break
            od[int(o.objectPCNId)] = o
        keys = od.keys()
        keys.sort()
        for oid in keys:
            o = od[oid]
            td = 'OFFLINE'
            db = 'N/A'
            nc = 'N/A'
            try:
                query = 'SELECT TOP(1) id,eventTime FROM _event_data_internal WHERE deviceId=%s ORDER BY eventTime DESC' % (str(o.objectMSId))
                c.execute(query)
                d = c.fetchall()
                if datetime.datetime.fromtimestamp(time.time()) - d[0][1] > datetime.timedelta(seconds=3600*24):
                    raise RuntimeError('xep')
                td = str(datetime.datetime.fromtimestamp(time.time()) - d[0][1]).split('.')[0]

                query = 'SELECT TOP(1) id,eventTime,db,nc FROM _gsm_data_internal WHERE deviceId=%s ORDER BY eventTime DESC' % (str(o.objectMSId))              
                c.execute(query)
                d = c.fetchall()
                
                db = d[0][2]
                nc = {'1':'MTS', '2':'Megafon'}.get(str(d[0][3]), 'N/A')
               
                online_ctr += 1
            except:
                offline_ctr += 1
            self.wfile.write('<tr><td class="tdblue">%s</td><td class="tdblue">%s</td><td class="tdred">%s</td><td class="tdblue">%s</td><td class="tdblue">%s</td></tr>' % (str(o.objectPCNId), str(o.objectMSId), str(td), str(db), str(nc)))
        #self.wfile.write('<h1>total:%d<br> online:%d<br> offline:%d</h1>' % (len(objects), online_ctr, offline_ctr))
        self.wfile.write('</table>') 
        self.wfile.write('<img src="http://glonass-nw.ru/photo/flite.gif">')
        #self.wfile.write('\n\n<a href="http://%s:%d/?mode_admin">admin mode</a>' % (globalHost, globalPort))

    def mode_admin(self):
        #reader = WorkerMSDB.Worker('192.168.4.5', '50359', 'transferTest', 'sa', 'ms-004')
        reader = WorkerMSDB.Worker('192.168.4.5', '52655', 'transferTest', 'sa', 'ms-004')
        reader.connect()

        test, normal = self.getObjects(reader.connection.cursor())
        objects = []
        for o in test:
            o.isTest = True
            objects.append(o)
        for o in normal:
            o.isTest = False
            objects.append(o)

        c = reader.connection.cursor()
        online_ctr = 0
        offline_ctr = 0
        self.wfile.write('<style type="text/css">')
        self.wfile.write('td.tdblue {color: #ffffff; background: #6699cc; font-family: Arial, sans-serif; font-weight: bold; font-size: 14px; }')
        self.wfile.write('td.tblue { color: #ffffff; background: #006699; font-family: Arial, sans-serif; font-weight: bold; font-size: 14px;}')
        self.wfile.write('td.tdred {FONT-WEIGHT: bold; FONT-SIZE: 14px; BACKGROUND: pink;  COLOR: #000000; FONT-FAMILY: Arial, sans-serif; }')
        self.wfile.write('</style>')
        self.wfile.write('<table border=1>')
        self.wfile.write('<tr><td class="tblue">Object</td><td class="tblue">Status</td><td class="tblue">Action</td></tr>')
        od = {}
        for o in objects:
            od[int(o.objectPCNId)] = o
        keys = od.keys()
        keys.sort()
        for oid in keys:
            o = od[oid]
            if o.isTest:
                self.wfile.write('<tr><td class="tdblue">%s</td><td class="tdblue">TEST</td><td class="tdred"> <a href="http://%s:%d/?mode_edit&make_norm&id=%s">make normal</a> </td></tr>' % (str(o.objectPCNId), globalHost, globalPort, str(o.objectPCNId)))
            else:
                self.wfile.write('<tr><td class="tdblue">%s</td><td class="tdblue">NORMAL</td><td class="tdred"> <a href="http://%s:%d/?mode_edit&make_test&id=%s">make test</a> </td></tr>' % (str(o.objectPCNId), globalHost, globalPort, str(o.objectPCNId)))
        self.wfile.write('</table>')
        self.wfile.write('\n\n<a href="http://%s:%d">back to operator mode</a>' % (globalHost, globalPort))

    def make_conv(self):
        raise RuntimeError('unused code')
        try:
            fIN = open('C:\\ms.online.test_objects.cfg', 'r')
        except:
            return
        norm_ids = []
        try:
            f = open('C:\\Magic\\ms.online.normal_objects.2.cfg', 'r')
            for o in f.readlines():
                o = o.strip()
                if len(o): norm_ids.append(o)
        except:
            pass
        for o in fIN.readlines():
            o = o.strip()
            if len(o) and not (o in norm_ids): norm_ids.append(o)
        f = open('ms.online.normal_objects.2.cfg', 'w')
        norm_ids.sort()
        for o in norm_ids:
            f.write('%s\n' % o)
        f.close()

    def make_test(self, oid):
        try:
            f = open('C:\\Magic\\ms.online.normal_objects.2.cfg', 'r')
        except:
            return

        norm_ids = []
        for o in f.readlines():
            o = o.strip()
            if len(o): norm_ids.append(o)
        if oid in norm_ids: norm_ids.remove(oid)
        f = open('C:\\Magic\\ms.online.normal_objects.2.cfg', 'w')
        norm_ids.sort()
        for o in norm_ids:
            f.write('%s\n' % o)
        f.close()

    def make_normal(self, oid):
        norm_ids = []
        try:
            f = open('C:\\Magic\\ms.online.normal_objects.2.cfg', 'r')
            for o in f.readlines():
                o = o.strip()
                if len(o): norm_ids.append(o)
        except:
            pass

        if not (oid in norm_ids): norm_ids.append(oid)
        f = open('C:\\Magic\\ms.online.normal_objects.2.cfg', 'w')
        norm_ids.sort()
        for o in norm_ids:
            f.write('%s\n' % o)
        f.close()

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        try:
            path = str(self.path).replace('?','').replace('/','')
            params = path.split('&')
            if len(params) > 0:
                globalObjectId = params[0]
                self.mode_normal(globalObjectId)                
            else: self.wfile.write('error: не задан номер объекта')
            
        except Exception, err:
            self.wfile.write('error: %s' % (str(err)))
        return





if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    servers = []
    server = HTTPServer((globalHost, globalPort), MyHandler)
    MSLogger.logInfo('ms online checker started at %s:%d, <Ctrl-C> to stop' % (globalHost, globalPort))
    server.serve_forever()
